package com.njtoyo.taxi.admin.library.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.logic.business.driver.DriverNotifyMessageLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.DriverNotifyMessage;
import com.njtoyo.taxi.admin.mapper.master.enums.driverNotifyMessage.State;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverNotifyMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class DriverNotifyMessageRunner implements ApplicationRunner {

    @Autowired
    private DriverNotifyMessageMapper driverNotifyMessageMapper;

    @Autowired
    private DriverNotifyMessageLogic driverNotifyMessageLogic;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        QueryWrapper<DriverNotifyMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", State.ready);
        queryWrapper.gt("regular_release_time", DateUtil.currentSeconds());
        List<DriverNotifyMessage> messages = driverNotifyMessageMapper.selectList(queryWrapper);
        log.info("项目重启时获取司机通知消息定时任务: {}", messages);
        if (!Objects.isNull(messages)) {
            messages.forEach(message -> {
                taskScheduler.schedule(() -> {
                    driverNotifyMessageLogic.send(message.getId());
                }, DateUtil.date(message.getRegularReleaseTime() * 1000));
            });
        }
    }
}
